<?php
declare(strict_types=1);
namespace SixShop\Wechat\Controller;

use app\model\User;
use SixShop\Wechat\Entity\ExtensionWechatUserEntity;
use SixShop\Wechat\Service\MiniApp;
use think\Request;
use think\Response;
use function SixShop\Core\success_response;
use function SixShop\Core\throw_logic_exception;

class UserController
{
    public function phoneNumber(Request $request, ExtensionWechatUserEntity $wechatUserEntity): Response
    {
        $code = $request->get('code/s');
        $user = User::find($request->userID);
        if ($user->mobile) {
            throw_logic_exception('手机号已绑定');
        }
        $phoneInfo = $wechatUserEntity->getPhoneNumber($code);
        $mobileUser = User::where(['mobile' => $phoneInfo['phoneNumber']])->findOrEmpty();
        if (!$mobileUser->isEmpty()) {
            if ($mobileUser->id != $request->userID) {
                throw_logic_exception('手机号已绑定其他账号');
            } else {
                throw_logic_exception('手机号已绑定');
            }
        }
        $user->mobile = $phoneInfo['phoneNumber'];
        $user->save();
        return success_response([
            'mobile' => $user->mobile,
        ]);
    }

    public function session(Request $request): Response
    {
        $params = $request->get([
            'code/s',
            'appid/s' => null,
        ]);
        $miniApp = app()->make(MiniApp::class, [$params['appid']]);
        $utils = $miniApp->getUtils();
        $response = $utils->codeToSession($params['code']);
        return success_response($response);
    }
}